package com.lee.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lee.Dto.LoginDTO;
import com.lee.common.lang.Result;
import com.lee.entity.User;
import com.lee.service.UserService;
import com.lee.utils.JwtUtils;
import freemarker.template.utility.SecurityUtilities;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.security.Security;

@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDTO loginDTO, HttpServletResponse response) {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDTO.getUsername()));

        Assert.notNull(user, "用户不存在");

        if (user == null || !user.getPassword().equals(SecureUtil.md5(loginDTO.getPassword()))) {
            return Result.error("密码错误");
        }
        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization", jwt);

        response.setHeader("Access-control-Expose-Headers", "Authorization");


        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map());

    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result loginout() {
        SecurityUtils.getSubject().logout();

        return Result.success(null);
    }
}
